"""
Copyright © 2021 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/micropython-espnow-practice-gui
"""
import os
from fontlib import FontLib

cli = '..\client\FontMaker_Cli.exe'

working_fontface = '文泉驿等宽正黑'
working_fontsize = 20
working_txt_file = 'txt\working.txt'
working_output_bin = 'working.bin'

iconfont_fontface = 'iconfont'
iconfont_fontsize = 20
iconfont_cst_file = 'txt\iconfont.cst'
iconfont_output_bin = 'iconfont.bin'

fontdata_output_file = 'fontdata_dict.py'

command_working = f'{cli} -f "{working_fontface}" -s {working_fontsize} --input {working_txt_file} -o {working_output_bin}'
command_iconfont = f'{cli} -f "{iconfont_fontface}" -s {iconfont_fontsize} --charset {iconfont_cst_file} -o {iconfont_output_bin}'


def generate_fontlib():
	try:
		if os.system(command_working) != 0:
			return False

		if os.system(command_iconfont) != 0:
			return False
	except OSError as ose:
		print(ose)
		return False

	return True

def generate_fontdata_dict():
	buffer_dict = {}

	chars = open(working_txt_file, 'r', encoding='utf-8').read().strip('\n')
	fontlib = FontLib(working_output_bin)
	buffer_dict.update(fontlib.get_characters(chars + '?'))

	chars = ''
	chars_cst = list(reversed(open(iconfont_cst_file, 'rb').read()))

	for index in range(0, len(chars_cst), 2):
		chars += chr(int.from_bytes(chars_cst[index: index + 2], 'big'))

	fontlib = FontLib(iconfont_output_bin)
	buffer_dict.update(fontlib.get_characters(chars))

	with open(fontdata_output_file, 'w', encoding='utf-8') as file:
		file.write('\t__DATA_DICT = {\n')
		for unicode, buffer in buffer_dict.items():
			comment = f'\t\t# {unicode}, {hex(unicode)}\n'
			data = f"\t\t'{chr(unicode)}': memoryview({bytes(buffer)}),\n"

			file.write(comment)
			file.write(data)
		file.write('\t}\n')


if __name__ == '__main__':
	if generate_fontlib():
		print('fontlib files generated')
		generate_fontdata_dict()
		print(f'fontdata file generated: {fontdata_output_file}')
	else:
		print('Generate fontlib file failed')
